package own.stu.jobgib.playown.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ReflectTest {
    public static void main(String[] args) throws Exception {

        ReflectTest t = new ReflectTest();
        t.test();
    }

    private void test() throws Exception {

        Integer num = new Integer(100);
        System.out.println(num);
        changeFinalFieldFake(num);
        System.out.println(num);
        System.out.println(" ----- ----- ------- ");
        num = new Integer(100);
        System.out.println(num);
        changeFinalField(num);
        System.out.println(num);
    }

    private void changeFinalFieldFake(Integer e) {
        e = 200;
    }

    private void changeFinalField(Integer e) throws NoSuchFieldException, IllegalAccessException {

        // 1 获取目标字段
        Field field = Integer.class.getDeclaredField("value");
        field.setAccessible(true);  // 设置字段可访问
        Field modifiersField = Field.class.getDeclaredField("modifiers");

        // 2 修改字段的修饰符
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

        // 3 修改字段的值
        field.set(e, 200);

        // 4 恢复字段的修饰符和final修饰符
        modifiersField.setInt(field, field.getModifiers() | Modifier.FINAL);  // 恢复final修饰符
        modifiersField.setAccessible(false);
        field.setAccessible(false);
    }
}
